package monitor

import (
	portainer "github.com/portainer/portainer/api"
	"github.com/portainer/portainer/api/bolt/internal"
	"github.com/portainer/portainer/api/bolt/errors"
	"github.com/boltdb/bolt"
)

const (
	// BucketName represents the name of the bucket where this service stores data.
	BucketName = "monitor"
)

// Service represents a service for managing schedule data.
type Service struct {
	connection *internal.DbConnection
}

// NewService creates a new instance of a service.
func NewService(connection *internal.DbConnection) (*Service, error) {
	err := internal.CreateBucket(connection, BucketName)
	if err != nil {
		return nil, err
	}

	return &Service{
		connection: connection,
	}, nil
}

func (service *Service) UpdateCPUMonitor(cpuStat portainer.CPUStat) error {
	identifier := internal.Itob(int(cpuStat.CPUStatTime))
	return internal.UpdateObject(service.connection, BucketName, identifier, cpuStat)
}

// StackByName returns a stack object by name.
func (service *Service) CPUStatLatest(UUID string) (*portainer.CPUStat, error) {
	var cpuStat *portainer.CPUStat

	err := service.connection.View(func(tx *bolt.Tx) error {
		bucket := tx.Bucket([]byte(BucketName))
		cursor := bucket.Cursor()
		//fmt.Println(bucket.Stats())
		//if bucket.Stats().KeyN < 2{
		//	return nil
		//}

		//_, v := cursor.Last()

		for k, v := cursor.Last(); k != nil; k, v = cursor.Prev() {
			var t portainer.CPUStat
			err := internal.UnmarshalObject(v, &t)
			if err != nil {
				return err
			}

			if t.UUID == UUID {
				cpuStat = &t
				break
			}
		}

		//err := internal.UnmarshalObject(v, &cpuStat)
		//if err != nil {
		//	return err
		//}

		if cpuStat == nil {
			return errors.ErrObjectNotFound
		}

		return nil
	})

	return cpuStat, err
}

func (service *Service) DeleteCPUStat(cpuStat portainer.CPUStat) error {
	identifier := internal.Itob(int(cpuStat.CPUStatTime))
	return internal.DeleteObject(service.connection, BucketName, identifier)
}